import 'package:flutter/material.dart';
import 'package:stacked/stacked.dart';
import 'package:vista/shared/models/message_shot.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/dialog_lens.dart';

/// 聊天视图模型
/// 管理单聊页面的数据和状态
class ChatViewModel extends BaseViewModel {
  final AuthFocus _authFocus;
  final DialogLens _dialogLens;
  final String otherUserId;

  ChatViewModel(this._authFocus, this._dialogLens, this.otherUserId);

  UserFrame? _currentUser;
  UserFrame? get currentUser => _currentUser;

  UserFrame? _otherUser;
  UserFrame? get otherUser => _otherUser;

  List<MessageShot> _messages = [];
  List<MessageShot> get messages => _messages;

  final TextEditingController _messageController = TextEditingController();
  TextEditingController get messageController => _messageController;

  /// 初始化数据
  Future<void> initialize() async {
    setBusy(true);
    try {
      _currentUser = await _authFocus.getCurrentUser();
      if (_currentUser == null) {
        setBusy(false);
        return;
      }

      final allUsers = await _authFocus.getUsers();
      _otherUser = allUsers.firstWhere(
        (u) => u.id == otherUserId,
        orElse: () => allUsers.first,
      );

      await _loadMessages();
      await _markAllAsRead();
    } finally {
      setBusy(false);
    }
  }

  /// 加载消息列表
  Future<void> _loadMessages() async {
    if (_currentUser == null) return;

    _messages = await _dialogLens.getChatMessages(
      userId1: _currentUser!.id,
      userId2: otherUserId,
    );
    notifyListeners();
  }

  /// 标记所有消息为已读
  Future<void> _markAllAsRead() async {
    if (_currentUser == null) return;

    await _dialogLens.markAllMessagesAsRead(
      userId: _currentUser!.id,
      otherUserId: otherUserId,
    );
  }

  /// 发送文本消息
  Future<void> sendMessage() async {
    if (_currentUser == null) return;
    final content = _messageController.text.trim();
    if (content.isEmpty) return;

    await _dialogLens.sendTextMessage(
      senderId: _currentUser!.id,
      receiverId: otherUserId,
      content: content,
    );

    _messageController.clear();
    await _loadMessages();
    notifyListeners();
  }

  /// 发送拨打失败消息
  Future<void> sendCallFailed() async {
    if (_currentUser == null) return;

    await _dialogLens.sendCallFailedMessage(
      senderId: _currentUser!.id,
      receiverId: otherUserId,
    );

    await _loadMessages();
    notifyListeners();
  }

  /// 刷新消息
  Future<void> refresh() async {
    await _loadMessages();
  }

  /// 删除所有消息
  Future<void> deleteAllMessages() async {
    if (_currentUser == null) return;

    await _dialogLens.deleteAllMessages(
      userId1: _currentUser!.id,
      userId2: otherUserId,
    );

    await _loadMessages();
    notifyListeners();
  }

  @override
  void dispose() {
    _messageController.dispose();
    super.dispose();
  }
}
